package com.ntt.benew.dictionary.view

import android.content.Context
import android.text.SpannableStringBuilder
import android.view.LayoutInflater
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.benew.ntt.evaluate.constant.EvalType
import com.benew.ntt.player.AudioItem
import com.benew.ntt.player.IAudioPlayListener
import com.benew.ntt.player.NttPlayCtrl
import com.benew.ntt.ydeval.listener.IEvalListener
import com.benew.ntt.ydeval.view.EvalEntity
import com.benew.ntt.ydeval.view.EvalManager
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.google.gson.internal.LinkedTreeMap
import com.google.gson.reflect.TypeToken
import com.ntt.benew.dictionary.R
import com.ntt.benew.dictionary.adapter.DictWordAdapter
import com.ntt.benew.dictionary.api.YDDictManager
import com.ntt.benew.dictionary.constants.Constants
import com.ntt.benew.dictionary.constants.LangType
import com.ntt.benew.dictionary.databinding.DictWordDetailViewBinding
import com.ntt.benew.dictionary.entity.DictWordEntity
import com.ntt.benew.dictionary.entity.WordSpellEntity
import com.ntt.benew.dictionary.listener.IAnalysisListener
import com.ntt.benew.dictionary.listener.IChildClickListener
import com.ntt.benew.dictionary.model.AnalysisModel
import com.ntt.benew.dictionary.utils.StringUtil
import com.ntt.benew.dictionary.utils.setDrawableBackground
import com.ntt.benew.dictionary.utils.setGradientDrawable
import com.ntt.core.nlogger.NLogger

/**
 * Created by Android Studio.
 * User: tw
 * Date: 2023/11/2
 * Time: 15:44
 */
class DictWordDetailView(context: Context) : BaseView(context), View.OnClickListener {

    private val TAG = javaClass.simpleName

    private var mBinding = DictWordDetailViewBinding.inflate(LayoutInflater.from(context), this)

    /**
     * 要查询的单词
     */
    private var mWord: String = ""

    /**
     * 美式发音 音频地址
     */
    private var usVoice: String? = ""

    /**
     * 英式发音 音频地址
     */
    private var bVoice: String? = ""

    /**
     * 单词拼读实体
     */
    private var mWordSpells: ArrayList<WordSpellEntity>? = null

    /**
     * 右侧recyclerview的适配器
     * 主要用于加载各种相关词
     */
    private var mAdapter: DictWordAdapter? = null

    /**
     *
     */
    private var mLinearLayoutManager: LinearLayoutManager? = null

    /**
     * recyclerview 子 view的点击监听
     */
    private val onIChildClickListener: IChildClickListener = object : IChildClickListener {
        override fun onChildClick(it: Any) {
            ToastUtils.showShort("点击了练习")
        }

    }

    init {
        initClick()
        initStyle()
        initAdapter()
        initModel()
        initEval()
        setBackgroundColor(ContextCompat.getColor(context, R.color.ntt_9926323F))
    }

    fun setData(word: String?) {
        initPlayListener()
        word?.let {
            mWord = it
            mBinding.tvWord.setText(it)
            queryWord(it)
        }
    }

    private fun initModel() {
        mModel = AnalysisModel()
    }

    private fun initStyle() {
        mBinding.run {
            clLeft.setGradientDrawable(20, ContextCompat.getColor(context, R.color.ntt_FFF8E5))
            clRight.setGradientDrawable(20, ContextCompat.getColor(context, R.color.ntt_FFF8E5))
            recyclerView.setGradientDrawable(
                20,
                ContextCompat.getColor(context, R.color.ntt_ffffff)
            )
        }
    }

    private fun initClick() {
        mBinding.ivClose.setOnClickListener(this)
        mBinding.ivSpelling.setOnClickListener(this)
        mBinding.ivEval.setOnClickListener(this)
        mBinding.enUsLayout.setOnClickListener(this)
        mBinding.enBritishLayout.setOnClickListener(this)
    }

    private fun initAdapter() {
        mAdapter = DictWordAdapter(context)
        mBinding.recyclerView.adapter = mAdapter
        mLinearLayoutManager = LinearLayoutManager(context)
        mBinding.recyclerView.layoutManager = mLinearLayoutManager
        mAdapter!!.mOnChildClickListener = onIChildClickListener
    }

    private fun initEval() {
        EvalManager.registerEvalListener(object : IEvalListener {
            override fun onClickPre() {
                NLogger.d(TAG)
            }

            override fun onClickNext() {
                NLogger.d(TAG)
            }

            override fun onClose(auto: Boolean) {
                NLogger.d(TAG)
            }

            override fun onEvalResult(
                score: Double,
                text: SpannableStringBuilder?,
                result: String?,
                evalEntity: EvalEntity?
            ) {
                NLogger.d(TAG)
            }

            override fun onRecordFile(filePath: String?) {
                NLogger.d(TAG)
            }

            override fun onDismiss() {
                NLogger.d(TAG)
                initPlayListener()
            }

            override fun onShow() {
                NLogger.d(TAG)
            }

            override fun onSoundEffect(enable: Boolean, sessionId: Int) {
                NLogger.d(TAG)
            }

            override fun onReleaseSoundEffect(sessionId: Int) {
                NLogger.d(TAG)
            }

        })
    }

    private fun initPlayListener() {
        NttPlayCtrl.setPlayAudioListener(object : IAudioPlayListener {
            override fun onComplete(url: String?, id: Long) {
                NLogger.d("播放完成回调！")
                mBinding.tvWord.setHLPositions(listOf())
            }

            override fun onPlaying(currAudio: AudioItem?) {
                NLogger.d("当前播放回调！${currAudio?.id}")
                currAudio?.takeIf { it.id != 0L }?.run {
                    mWordSpells?.let {
                        mBinding.tvWord.setHLPositions(it[(id - 1).toInt()].position)
                    }
                } ?: kotlin.run {
                    val positions = arrayListOf<Int>()
                    mWord.indices.forEach {
                        positions.add(it)
                    }
                    mBinding.tvWord.setHLPositions(positions)
                }


            }
        })
    }

    private fun clearPlayerListener() {
        NttPlayCtrl.setPlayAudioListener(null)
    }

    override fun onClick(p0: View) {
        when (p0.id) {
            mBinding.ivClose.id -> {
                clearPlayerListener()
                mICallback?.dismiss(this)
            }

            mBinding.ivSpelling.id -> {
                mWordSpells?.let { spells ->
                    val audioItems: MutableList<AudioItem> = mutableListOf()
                    spells.forEachIndexed { index, it ->
                        audioItems.add(
                            AudioItem(url = it.sound, id = index.toLong() + 1)
                        )
                    }
                    audioItems.add(
                        AudioItem(url = usVoice)
                    )
                    NttPlayCtrl.playAudios(audioItems)
                }

            }

            mBinding.enUsLayout.id -> NttPlayCtrl.playAudio(AudioItem(bVoice))
            mBinding.enBritishLayout.id -> NttPlayCtrl.playAudio(AudioItem(usVoice))
            mBinding.ivEval.id -> {
                EvalManager.startEval(
                    EvalEntity(
                        mWord, if (StringUtil.isPureChinese(mWord)) {
                            EvalType.ZH_CHS
                        } else {
                            EvalType.EN_WORD
                        }
                    )
                )
            }
        }
    }


    /**
     * 开始查词
     */
    private fun queryWord(word: String) {
        mModel?.postQueryDictWord(word, getDefaultLang(word), object : IAnalysisListener {
            override fun onSuccess(data: String?) {
                NLogger.d("查词接口返回数据！$data")
                val dataGson = GsonUtils.fromJson<Map<String, Any>>(
                    data,
                    object : TypeToken<Map<String, Any>>() {}.type
                )
                if (dataGson["errorCode"] == 0 || dataGson.containsKey("result")) {
                    updateUi(dataGson["result"] as ArrayList<*>)
                } else {
                    ToastUtils.showShort("接口请求出错！错误码：${dataGson["errorCode"]}")
                }

            }

        })

    }

    /**
     * 获取语言类型
     */
    private fun getDefaultLang(word: String?): String {
        return word?.run {
            val noSignWord = StringUtil.formatToRemoveSign(word)
            if (StringUtil.isPureChinese(noSignWord)) YDDictManager.LANG_ZH_CHS else YDDictManager.LANG_EN
        } ?: YDDictManager.LANG_EN
    }

    /**
     * 查词数据回调，更新ui
     */
    private fun updateUi(result: ArrayList<*>) {
        if (result.isEmpty()) {
            return
        }
        val resultItem = result[0] as LinkedTreeMap<*, *>
        // 加载封面
        Glide.with(this).load(resultItem["image"]).error(R.drawable.icon_default_img)
            .into(mBinding.ivCover)
        if (!resultItem.containsKey("details")) {
            return
        }
        val detailArray = resultItem["details"] as ArrayList<*>
        if (detailArray.size == 0) {
            return
        }
        val detailItem = detailArray[0] as LinkedTreeMap<*, *>
        parseWordOrSpell(detailItem)
        parseYDVoice(detailItem)
        parseWordData(detailItem)

    }

    /**
     * 解析数据，提取各个需要的列表数据
     */
    private fun parseWordData(detailItem: LinkedTreeMap<*, *>) {
        val mAdapterData: MutableList<DictWordEntity> = mutableListOf()
        if (detailItem.containsKey("meanings")) {
            val entity = DictWordEntity()
            entity.values = detailItem["meanings"] as ArrayList<*>
            entity.type = Constants.TYPE_EXPLAIN_ITEM
            entity.titleTxt = "释义"
            mAdapterData.add(entity)
        }
        if (detailItem.containsKey("phrases")) {
            val entity = DictWordEntity()
            entity.values = detailItem["phrases"] as ArrayList<*>
            entity.type = Constants.TYPE_PHRASE_ITEM
            entity.titleTxt = "词组"
            mAdapterData.add(entity)
        }
        if (detailItem.containsKey("derivatives")) {
            val entity = DictWordEntity()
            entity.values = detailItem["derivatives"] as ArrayList<*>
            entity.type = Constants.TYPE_EXPAND_ITEM
            entity.titleTxt = "拓展"
            mAdapterData.add(entity)
        }
        if (detailItem.containsKey("relatedWords")) {
            val entity = DictWordEntity()
            val relatedWords = detailItem["relatedWords"] as LinkedTreeMap<*, *>
            if (relatedWords.containsKey("words")) {
                entity.values = relatedWords["words"] as ArrayList<*>
                entity.type = Constants.TYPE_RELATED_ITEM
                entity.titleTxt = "相关词"
                mAdapterData.add(entity)
            }
        }
        mLinearLayoutManager?.scrollToPosition(0)
        mAdapter?.setNewData(mAdapterData)

    }

    /**
     * 从有道返回的数据中获取发音 音频链接
     */
    private fun parseYDVoice(detailItem: LinkedTreeMap<*, *>) {
        // 英式音标
        var phonetic: String = ""
        // 美式音标
        var usPhonetic: String = ""

        //优先获取美式发音
        if (detailItem.containsKey("usVoice") && detailItem["usVoice"] != null) {
            val ukVoice = detailItem["usVoice"] as ArrayList<*>
            ukVoice.takeIf {
                it.isNotEmpty()
            }?.run {
                val voiceItem = this[0] as LinkedTreeMap<*, *>
                if (voiceItem.containsKey("voice")) {
                    usVoice = voiceItem["voice"] as String
                }
                if (voiceItem.containsKey("usPhonetic")) {
                    usPhonetic = voiceItem["usPhonetic"] as String
                }
            }
        }
        //英式发音
        if (detailItem.containsKey("voice") && detailItem["voice"] != null) {
            val voice = detailItem["voice"] as ArrayList<*>
            voice.takeIf { it.isNotEmpty() }?.run {
                val voiceItem = this[0] as LinkedTreeMap<*, *>
                if (voiceItem.containsKey("voice")) {
                    bVoice = voiceItem["voice"] as String
                }
                if (voiceItem.containsKey("phonetic")) {
                    phonetic = voiceItem["phonetic"] as String
                }
            }
        }
        mBinding.run {
            val colorsB = intArrayOf(
                ContextCompat.getColor(context, R.color.ntt_FFCC00),
                ContextCompat.getColor(context, R.color.ntt_FFB604)
            )
            // 设置渐变背景
            enBritishLayout.setDrawableBackground(colorsB, SizeUtils.dp2px(18f).toFloat())
            val colorsUs = intArrayOf(
                ContextCompat.getColor(context, R.color.ntt_84D1FF),
                ContextCompat.getColor(context, R.color.ntt_4DBCFD),
            )
            enUsLayout.setDrawableBackground(colorsUs, SizeUtils.dp2px(18f).toFloat())
            tvBPhonetic.text = "英[$phonetic]"
            tvUsPhonetic.text = "美[$usPhonetic]"
        }
    }

    /**
     * 解析有道返回的单词拼写
     */
    private fun parseWordOrSpell(detailItem: LinkedTreeMap<*, *>) {
        if (!detailItem.containsKey("spell")) {
            return
        }
        val spell = GsonUtils.toJson(detailItem["spell"])
        mWordSpells =
            GsonUtils.fromJson<ArrayList<WordSpellEntity>>(
                spell,
                object : TypeToken<ArrayList<WordSpellEntity>>() {}.type
            )

    }

    /**
     * 渲染释义模块
     */
//    private fun renderExplain(detailItem: LinkedTreeMap<*, *>): View? {
//        if (!detailItem.containsKey("meanings")) {
//            return null
//        }
//        val explainView = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL }
//        val meanings = detailItem["meanings"] as ArrayList<*>?
//        meanings?.let { array ->
//            //创建释义标题
//            val title = WordDetailTitleView(context).apply {
//                setText("释义")
//            }
//            explainView.addView(title)
//            array.forEach { item ->
//                // 创建释义item行
//                val explainLayout = LinearLayout(context)
//                explainLayout.orientation = LinearLayout.HORIZONTAL
//                explainLayout.setPadding(SizeUtils.dp2px(40f), SizeUtils.dp2px(10f), 0, 0)
//
//                item as LinkedTreeMap<*, *>
//
//                val pos = item["pos"] as String?
//                val values = item["value"] as ArrayList<*>?
//                var txt = pos
//                values?.forEach {
//                    it as String
//                    txt += it
//                }
//
//                val explainTxt = BorderedTextView(context)
//                explainTxt.text = txt
//
//                val gptButton = TextView(context).apply {
//                    val colors = intArrayOf(
//                        ContextCompat.getColor(context, R.color.ntt_FFCC00),
//                        ContextCompat.getColor(context, R.color.ntt_FFB604)
//                    )
//                    setDrawableBackground(colors, SizeUtils.dp2px(20f).toFloat())
//                    text = "GPT练习"
//                    setTextColor(ContextCompat.getColor(context, R.color.ntt_ffffff))
//                    textSize = 18f
//                    typeface = Typeface.defaultFromStyle(Typeface.BOLD)
//                    setPadding(
//                        SizeUtils.dp2px(18f),
//                        SizeUtils.dp2px(8f),
//                        SizeUtils.dp2px(18f),
//                        SizeUtils.dp2px(8f)
//                    )
//                    layoutParams =
//                        LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT).apply {
//                            marginStart = SizeUtils.dp2px(20f)
//                        }
//                }
//                explainLayout.addView(explainTxt)
//                explainLayout.addView(gptButton)
//                explainView.addView(explainLayout)
//
//            }
//        }
//        return explainView
//    }

    /**
     * 渲染词组模块
     */
//    private fun renderPhrase(detailItem: LinkedTreeMap<*, *>): View? {
//        if (!detailItem.containsKey("phrases")){
//            return null
//        }
//        val
//        val phrases = detailItem["phrases"] as ArrayList<*>?
//        phrases?.forEach {
//            it as LinkedTreeMap<*, *>
//            it.
//        }
//    }


}